package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {

    private final static String GRANT_TYPE = "password";

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过密码认证
     *
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @Override
    public AuthToken login(String clientId, String clientSecret, String username, String password) {
        try {
            //localhost:9001/oauth/token   密码授权 -----发送httpclient请求 获取access_token
            ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
            String path = serviceInstance.getUri().toString();
            String url = path + "/oauth/token";

            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();

            //封装头信息

            // 封装请求数据
            byte[] encode = Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes());
            String clientEncode = new String(encode, "UTF-8");
            headers.add("Authorization", "Basic " + clientEncode);


            //封装请求参数
            body.add("grant_type", GRANT_TYPE);
            body.add("username", username);
            body.add("password", password);



            HttpEntity requestEntity = new HttpEntity(body, headers);
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

            Map map = responseEntity.getBody();

            AuthToken authToken =  new AuthToken();
            authToken.setAccessToken(map.get("access_token").toString());
            authToken.setTokenType(map.get("token_type").toString());
            authToken.setRefreshToken(map.get("refresh_token").toString());
            authToken.setRefreshToken(map.get("jti").toString());

            return authToken;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }


}
